const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

/**
 * 获取所有角色
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAllRoles = async (req, res) => {
  try {
    const roles = await prisma.role.findMany({
      include: {
        permissions: {
          include: {
            permission: true
          }
        },
        _count: {
          select: {
            users: true
          }
        }
      }
    });
    
    // 格式化返回数据
    const formattedRoles = roles.map(role => ({
      id: role.id,
      name: role.name,
      description: role.description,
      isSystem: role.isSystem,
      userCount: role._count.users,
      permissions: role.permissions.map(rp => ({
        id: rp.permission.id,
        code: rp.permission.code,
        name: rp.permission.name,
        group: rp.permission.group
      })),
      createdAt: role.createdAt,
      updatedAt: role.updatedAt
    }));
    
    return res.json({
      status: 'success',
      data: formattedRoles
    });
  } catch (error) {
    console.error('获取角色列表失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '获取角色列表失败',
      error: error.message
    });
  }
};

/**
 * 获取单个角色
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getRoleById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const role = await prisma.role.findUnique({
      where: { id: parseInt(id) },
      include: {
        permissions: {
          include: {
            permission: true
          }
        },
        users: {
          select: {
            id: true,
            username: true,
            name: true
          }
        }
      }
    });
    
    if (!role) {
      return res.status(404).json({
        status: 'error',
        message: '角色不存在'
      });
    }
    
    // 格式化返回数据
    const formattedRole = {
      id: role.id,
      name: role.name,
      description: role.description,
      isSystem: role.isSystem,
      permissions: role.permissions.map(rp => ({
        id: rp.permission.id,
        code: rp.permission.code,
        name: rp.permission.name,
        group: rp.permission.group
      })),
      users: role.users,
      createdAt: role.createdAt,
      updatedAt: role.updatedAt
    };
    
    return res.json({
      status: 'success',
      data: formattedRole
    });
  } catch (error) {
    console.error('获取角色失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '获取角色失败',
      error: error.message
    });
  }
};

/**
 * 创建角色
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.createRole = async (req, res) => {
  try {
    const { name, description, permissionIds = [] } = req.body;
    
    // 验证必填字段
    if (!name) {
      return res.status(400).json({
        status: 'error',
        message: '角色名称为必填项'
      });
    }
    
    // 检查名称是否已存在
    const existingRole = await prisma.role.findUnique({
      where: { name }
    });
    
    if (existingRole) {
      return res.status(400).json({
        status: 'error',
        message: '角色名称已存在'
      });
    }
    
    // 验证权限ID是否存在
    if (permissionIds.length > 0) {
      const permissions = await prisma.permission.findMany({
        where: {
          id: { in: permissionIds.map(id => parseInt(id)) }
        }
      });
      
      if (permissions.length !== permissionIds.length) {
        return res.status(400).json({
          status: 'error',
          message: '部分权限ID不存在'
        });
      }
    }
    
    // 使用事务来创建角色和权限关联
    const result = await prisma.$transaction(async (tx) => {
      // 创建角色
      const newRole = await tx.role.create({
        data: {
          name,
          description,
          isSystem: false
        }
      });
      
      // 创建权限关联
      const permissionConnections = permissionIds.map(permissionId => ({
        roleId: newRole.id,
        permissionId: parseInt(permissionId)
      }));
      
      if (permissionConnections.length > 0) {
        await tx.rolePermission.createMany({
          data: permissionConnections
        });
      }
      
      // 获取包含权限的完整角色信息
      return await tx.role.findUnique({
        where: { id: newRole.id },
        include: {
          permissions: {
            include: {
              permission: true
            }
          }
        }
      });
    });
    
    // 格式化返回数据
    const formattedRole = {
      id: result.id,
      name: result.name,
      description: result.description,
      isSystem: result.isSystem,
      permissions: result.permissions.map(rp => ({
        id: rp.permission.id,
        code: rp.permission.code,
        name: rp.permission.name,
        group: rp.permission.group
      })),
      createdAt: result.createdAt,
      updatedAt: result.updatedAt
    };
    
    return res.status(201).json({
      status: 'success',
      message: '角色创建成功',
      data: formattedRole
    });
  } catch (error) {
    console.error('创建角色失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '创建角色失败',
      error: error.message
    });
  }
};

/**
 * 更新角色
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateRole = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, description, permissionIds } = req.body;
    
    // 检查角色是否存在
    const role = await prisma.role.findUnique({
      where: { id: parseInt(id) }
    });
    
    if (!role) {
      return res.status(404).json({
        status: 'error',
        message: '角色不存在'
      });
    }
    
    // 如果更改名称，检查是否已存在
    if (name && name !== role.name) {
      const existingRole = await prisma.role.findUnique({
        where: { name }
      });
      
      if (existingRole) {
        return res.status(400).json({
          status: 'error',
          message: '角色名称已存在'
        });
      }
    }
    
    // 验证权限ID是否存在
    if (permissionIds && permissionIds.length > 0) {
      const permissions = await prisma.permission.findMany({
        where: {
          id: { in: permissionIds.map(id => parseInt(id)) }
        }
      });
      
      if (permissions.length !== permissionIds.length) {
        return res.status(400).json({
          status: 'error',
          message: '部分权限ID不存在'
        });
      }
    }
    
    // 使用事务来更新角色和权限关联
    const result = await prisma.$transaction(async (tx) => {
      // 准备更新数据
      const updateData = {};
      
      if (name) updateData.name = name;
      if (description !== undefined) updateData.description = description;
      
      // 更新角色基本信息
      const updatedRole = await tx.role.update({
        where: { id: parseInt(id) },
        data: updateData
      });
      
      // 如果提供了权限IDs，更新权限关联
      if (permissionIds) {
        // 删除现有权限关联
        await tx.rolePermission.deleteMany({
          where: { roleId: parseInt(id) }
        });
        
        // 创建新权限关联
        const permissionConnections = permissionIds.map(permissionId => ({
          roleId: parseInt(id),
          permissionId: parseInt(permissionId)
        }));
        
        if (permissionConnections.length > 0) {
          await tx.rolePermission.createMany({
            data: permissionConnections
          });
        }
      }
      
      // 获取包含权限的完整角色信息
      return await tx.role.findUnique({
        where: { id: parseInt(id) },
        include: {
          permissions: {
            include: {
              permission: true
            }
          }
        }
      });
    });
    
    // 格式化返回数据
    const formattedRole = {
      id: result.id,
      name: result.name,
      description: result.description,
      isSystem: result.isSystem,
      permissions: result.permissions.map(rp => ({
        id: rp.permission.id,
        code: rp.permission.code,
        name: rp.permission.name,
        group: rp.permission.group
      })),
      createdAt: result.createdAt,
      updatedAt: result.updatedAt
    };
    
    return res.json({
      status: 'success',
      message: '角色更新成功',
      data: formattedRole
    });
  } catch (error) {
    console.error('更新角色失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '更新角色失败',
      error: error.message
    });
  }
};

/**
 * 删除角色
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteRole = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查角色是否存在
    const role = await prisma.role.findUnique({
      where: { id: parseInt(id) },
      include: {
        _count: {
          select: {
            users: true
          }
        }
      }
    });
    
    if (!role) {
      return res.status(404).json({
        status: 'error',
        message: '角色不存在'
      });
    }
    
    // 检查是否有用户关联此角色
    if (role._count.users > 0) {
      return res.status(400).json({
        status: 'error',
        message: '无法删除角色，请先移除关联的用户'
      });
    }
    
    // 使用事务来删除角色和权限关联
    await prisma.$transaction(async (tx) => {
      // 删除角色-权限关联
      await tx.rolePermission.deleteMany({
        where: { roleId: parseInt(id) }
      });
      
      // 删除角色
      await tx.role.delete({
        where: { id: parseInt(id) }
      });
    });
    
    return res.json({
      status: 'success',
      message: '角色删除成功'
    });
  } catch (error) {
    console.error('删除角色失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '删除角色失败',
      error: error.message
    });
  }
};

/**
 * 获取所有权限
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getAllPermissions = async (req, res) => {
  try {
    const permissions = await prisma.permission.findMany({
      orderBy: {
        group: 'asc'
      }
    });
    
    // 按分组整理权限
    const groupedPermissions = {};
    
    permissions.forEach(permission => {
      if (!groupedPermissions[permission.group]) {
        groupedPermissions[permission.group] = [];
      }
      
      groupedPermissions[permission.group].push({
        id: permission.id,
        code: permission.code,
        name: permission.name,
        description: permission.description
      });
    });
    
    return res.json({
      status: 'success',
      data: groupedPermissions
    });
  } catch (error) {
    console.error('获取权限列表失败:', error);
    return res.status(500).json({
      status: 'error',
      message: '获取权限列表失败',
      error: error.message
    });
  }
}; 